/**
 *
 */
package com.ybkj.daijia.server.service.impl;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.service.MemberPaymentsRecordService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Shine
 *
 */
@Service
public class DefaultMemberPaymentsRecordService implements MemberPaymentsRecordService {

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private PassengerApi passengerApi;

//	@Transactional(rollbackFor=Exception.class)
//	public MemberPaymentsRecord insertRecord(MemberPaymentsRecord memberPaymentsRecord) {
//	
//		memberPaymentsRecordMapper.insertRecord(memberPaymentsRecord);
//	
//		return memberPaymentsRecord;
//	}

//	@Override
//	@Transactional(rollbackFor=Exception.class)
//	public int updateByPrimaryKey(MemberPaymentsRecord record) {
//		
//		return memberPaymentsRecordMapper.updateByPrimaryKey(record);
//	}

//	@Transactional(rollbackFor=Exception.class)
//	public void batchInsertRecord(List<MemberPaymentsRecord> recordlist) {
//
//		memberPaymentsRecordMapper.batchInsertRecord(recordlist);
//	}

//	@Override
//	public MemberPaymentsRecord findOne(Long id) {
//		
//		return memberPaymentsRecordMapper.selectByPrimaryKey(id);
//	}

    @Override
    public Page<PassengerAccount> queryByPassenger(Long passengerId, String different, Date start,
        Date end, Integer page, Integer limit) {

        Pageable pageable = null;
        if (null != page && null != limit) {
            pageable = new PageRequest(page, limit);
        }

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.QUERY_PASSENGER_ACCOUNT;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passengerId));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        if (null != page && null != limit) {
            kv.put("page", String.valueOf(page + 1));
            kv.put("rows", String.valueOf(limit));

            sb.append("&page={page}");
            sb.append("&rows={rows}");
        }

        if (StringUtils.isNotBlank(different)) {
            kv.put("different", String.valueOf(different));
            sb.append("&different={different}");
        }
        if (null != start) {
            kv.put("start", String.valueOf(start.getTime()));
            sb.append("&start={start}");
        }
        if (null != end) {
            kv.put("end", String.valueOf(end.getTime()));
            sb.append("&end={end}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerAccount> content = new ArrayList<PassengerAccount>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerAccount>>() {
                }.getType());
            }
        }

        return new PageImpl<PassengerAccount>(content, pageable, total);
    }

    @Override
    public Page<PassengerAccount> queryByEnterprise(Long enterpriseId, String different, Date start,
        Date end, Integer page, Integer limit) {

        Pageable pageable = null;
        if (null != page && null != limit) {
            pageable = new PageRequest(page, limit);
        }

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.QUERY_ENTERPRISE_ACCOUNT;
        api = api.replaceAll("\\{enterpriseId\\}", String.valueOf(enterpriseId));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();

        if (null != page && null != limit) {
            kv.put("page", String.valueOf(page + 1));
            kv.put("rows", String.valueOf(limit));

            sb.append("&page={page}");
            sb.append("&rows={rows}");
        }

        if (StringUtils.isNotBlank(different)) {
            kv.put("different", String.valueOf(different));
            sb.append("&different={different}");
        }
        if (null != start) {
            kv.put("start", String.valueOf(start.getTime()));
            sb.append("&start={start}");
        }
        if (null != end) {
            kv.put("end", String.valueOf(end.getTime()));
            sb.append("&end={end}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerAccount> content = new ArrayList<PassengerAccount>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerAccount>>() {
                }.getType());
            }
        }

        return new PageImpl<PassengerAccount>(content, pageable, total);
    }

//	@Override
//	public List<MemberPaymentsRecord> queryAllByMember(Long memberId) {
//		
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("memberId", memberId);
//		params.put("type", null);
//		
//		List<MemberPaymentsRecord> content = memberPaymentsRecordMapper.selectByMember(params);
//		
//		return content;
//	}

//	@Override
//	public Page<MemberPaymentsRecord> queryByMemberAndType(Long memberId,String type,Date start,Date end) {
//		
//		Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
//		
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("memberId", memberId);
//		params.put("type", type);
//		if(start != null){
//			params.put("start", start);
//		}
//		if(end != null){
//			params.put("end", end);
//		}
//		params.put("offset", Pager.getOffset());
//		params.put("size", Pager.getLimit());
//		
//		List<MemberPaymentsRecord> content = memberPaymentsRecordMapper.selectByMember(params);
//		long total = memberPaymentsRecordMapper.countByMember(params);
//		
//		return new PageImpl<MemberPaymentsRecord>(content, pageable, total);
//		
//	}

    @Override
    public Page<Map<String, Object>> pagePaymentsByMember(Long passengerId, Integer page,
        Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.QUERY_PASSENGER_ACCOUNT;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passengerId));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();

        kv.put("page", String.valueOf(page));
        kv.put("rows", String.valueOf(limit));

        String resultStr = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerAccount> content = new ArrayList<PassengerAccount>();
        long total = 0;

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerAccount>>() {
                }.getType());
            }
        }

//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("memberId", memberId);
//		params.put("offset", page*limit);
//		params.put("size", limit);
//		
//		List<MemberPaymentsRecord> content = memberPaymentsRecordMapper.selectByMember(params);
//		long total = memberPaymentsRecordMapper.countByMember(params);

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(content)) {

            for (PassengerAccount passengerAccount : content) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("recordId", passengerAccount.getId());
                map.put("recordCreatedStr", passengerAccount.getCreated());
                map.put("recordMoney", passengerAccount.getMoney());
                map.put("recordBalance", (new BigDecimal(passengerAccount.getAfterDrawMoney())
                    .add(new BigDecimal(passengerAccount.getAfterNoDrawMoney())))
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("recordFollowNo", passengerAccount.getTradeNo());
                map.put("recirdOrderNo", passengerAccount.getOrderNo());
                map.put("recordMemo", HtmlHelper.html2Text(passengerAccount.getDetails()));
                map.put("recordPayType", passengerAccount.getPayTypeStr());
                if (passengerAccount.getMoney().doubleValue() > 0) {
                    map.put("recordType", 1);
                } else {
                    map.put("recordType", 0);
                }
                mapList.add(map);
            }
        }

        Page<Map<String, Object>> result = new PageImpl<Map<String, Object>>(mapList, pageable,
            total);

        return result;

    }

    @Override
    public Page<Map<String, Object>> pagePaymentsByMemberV5(Long passengerId, Integer page,
        Integer limit, String payType) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.QUERY_PASSENGER_ACCOUNT;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passengerId));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page));
        kv.put("rows", String.valueOf(limit));

        // 如果有指定的流水类型时，指定类型
        if (null != payType) {
            kv.put("payType", payType);
            sb.append("&payType={payType}");
        }

        String resultStr = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerAccount> content = new ArrayList<PassengerAccount>();
        long total = 0;

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerAccount>>() {
                }.getType());
            }
        }

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(content)) {
            for (PassengerAccount passengerAccount : content) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("recordId", passengerAccount.getId());
                map.put("recordCreatedStr", passengerAccount.getCreated());
                map.put("recordMoney", passengerAccount.getMoney());
                map.put("recordBalance", (new BigDecimal(passengerAccount.getAfterDrawMoney())
                    .add(new BigDecimal(passengerAccount.getAfterNoDrawMoney())))
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("recordFollowNo", passengerAccount.getTradeNo());
                map.put("recirdOrderNo", passengerAccount.getOrderNo());
                map.put("recordMemo", HtmlHelper.html2Text(passengerAccount.getDetails()));
                map.put("recordPayType", passengerAccount.getPayTypeStr());
                if (passengerAccount.getMoney().doubleValue() > 0) {
                    map.put("recordType", 1);
                } else {
                    map.put("recordType", 0);
                }
                mapList.add(map);
            }
        }
        Page<Map<String, Object>> result = new PageImpl<Map<String, Object>>(mapList, pageable,
            total);
        return result;
    }

//	@Override
//	public MemberPaymentsRecord findByTypeAndOrderId(String type,
//			Long orderId) {
//		return memberPaymentsRecordMapper.selectByTypeAndOrderId(type,orderId);
//	}

//	@Override
//	public List<MemberPaymentsRecord> findMoreByTypeAndOrderId(String type,Long orderId) {
//		return memberPaymentsRecordMapper.selectMoreByTypeAndOrderId(type,orderId);
//	}


}
